package com.example.venue_reservation_service.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Calendar;

@Component
public class JwtUtil {
    private static final String secret = "Ij7qznGfxwRvC9jvfxESAXUYAS";
    /**
     * 生成jwt token
     */
    public static String createToken(int userId){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);//设置7天过期时间
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withAudience(String.valueOf(userId))
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));//sign
        return token;
    }

    /**
     * 验证token 合法性
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }

    public static Integer getUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        return Integer.parseInt(JWT.decode(authorization).getAudience().get(0));
    }
}
